<template>
    <div>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="头像" prop="Image">
                        <el-upload class="avatar-uploader" :action="baseapi + '/Files'" :show-file-list="false"
                            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                            <img v-if="ruleForm.Image" :src="baseImg + ruleForm.Image" class="avatar" />
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="用户名" prop="UserName">
                        <el-input v-model="ruleForm.UserName" placeholder="请输入用户名"></el-input>
                    </el-form-item>
                    <el-form-item label="性别" prop="sex">
                        <el-radio-group v-model="ruleForm.sex">
                            <el-radio label="男"></el-radio>
                            <el-radio label="女"></el-radio>
                        </el-radio-group>
                    </el-form-item>

                </el-col>
                <el-col :span="12">
                    <el-form-item label="出生日期" required>
                        <el-form-item prop="birthday" style="width: 200px;">
                            <el-date-picker type="datetime" placeholder="选择出生日期" v-model="ruleForm.birthday"
                                style="width: 100%;"></el-date-picker>
                        </el-form-item>
                    </el-form-item>

                    <el-form-item label="手机号码" prop="phone">
                        <el-input v-model="ruleForm.phone" placeholder="请输入手机号"></el-input>
                    </el-form-item>
                    <el-form-item label="账号" prop="loginName">
                        <el-input v-model="ruleForm.loginName" placeholder="请输入账号"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="warning" plain @click="submitForm('ruleForm')">更新数据</el-button>
                        <el-button @click="resetForm('ruleForm')">重置</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>
<script>
import basepath from '@/plugins/base.js'
import { mapMutations } from "vuex";
export default {
    nam: 'Upd',
    data() {
        return {
            baseapi: '',
            baseImg: '',
            ruleForm: {},
            User: {},
            rules: {
                UserName: [{
                    required: true,
                    message: '请输入姓名',
                    trigger: 'blur'
                },
                {
                    min: 2,
                    max: 5,
                    message: '长度在 2 到 5 个字符',
                    trigger: 'blur'
                }
                ],
                loginName: [{
                    required: true,
                    message: '请输入登录昵称',
                    trigger: 'blur'
                },
                {
                    min: 2,
                    max: 5,
                    message: '长度在 2 到 5 个字符',
                    trigger: 'blur'
                }
                ],
                // birthday: [{
                // 	type: 'date',
                // 	required: true,
                // 	message: '请选择日期',
                // 	trigger: 'change'
                // }],
                phone: [{
                    required: true,
                    message: '请输入手机号码',
                    trigger: 'blur'
                },
                {
                    min: 11,
                    max: 11,
                    message: '长度在为11位数字',
                    trigger: 'blur'
                }
                ]
            }
        }
    },
    methods: {
        ...mapMutations(["setUser"]),
        //上传成功
        handleAvatarSuccess(res, file) {
            console.log(file)
            if (res.code == 1) {
                this.$notify.success({ title: '成功', message: '图片上传成功!' })
                this.ruleForm.Image = res.data;
            } else {
                this.$message.error(res.msg);
            }
        },
        //上传之前
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isPNG = file.type === 'image/png';

            const isLtMB = file.size / 1024 / 1024 < 10;

            if (!isJPG && !isPNG) {
                this.$notify.error({ title: '失败', message: '上传头像图片只能是 JPG 和 PNG 格式!' })
            }
            if (!isLtMB) {
                this.$notify.error({ title: '失败', message: '上传头像图片大小不能超过 10MB!' })
            }
            return (isJPG || isPNG) && isLtMB;
        },
        //重置表单
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        //提交表单
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.axios({
                        method: 'Put',
                        url: 'Users',
                        data: JSON.stringify(this.ruleForm),
                        headers: {
                            Authorization: sessionStorage.getItem('token'),
                            'Content-Type': 'application/json'
                        }
                    }).then(res => {
                        if (res.data.msg == '用户信息更改成功！') {
                            this.$notify({
                                title: '成功',
                                message: res.data.msg,
                                type: 'success'
                            });
                            /* 改变父窗口的值来关闭弹窗 */
                            this.$emit("change", false);
                            this.$alert('信息已修改，即将退出登录！', '提示', {
                                confirmButtonText: '确定',
                                callback: action => {
                                    console.log(action)
                                    sessionStorage.clear();
                                    this.setUser({
                                        UserId: null,
                                        loginName: null,
                                        loginPwd: null,
                                        UserName: null,
                                        Roles: null,
                                        RoleName: null,
                                        DeptName: null,
                                        imgPath: null,
                                        Token: null,
                                        Exp: null,
                                        sex: null,
                                        birthday: null,
                                        phone: null,
                                        imgID: null,
                                        lastTime: null,
                                        status: null,
                                    });
                                    location.href = "/login";
                                }
                            });
                        } else {
                            this.$notify.error({
                                title: '错误',
                                message: res.data.msg
                            });
                        }
                    }).catch(err => {
                        console.log('err: ', err);
                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
    },
    model: {
        prop: "dialogFormVisible",
        event: "change",
    },
    props: {
        dialogFormVisible: Boolean,
        data: Object,
    },
    watch: {
        dialogFormVisible(v) {
            if (v) this.ruleForm = JSON.parse(JSON.stringify(this.data));
        }
    },
    created() {
        this.baseapi = basepath.apiUrl;
        this.baseImg = basepath.imgUrl;
        this.ruleForm = JSON.parse(JSON.stringify(this.data));
        console.log(JSON.parse(JSON.stringify(this.data)));
    }
}
</script>
<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>